﻿using GenericHtml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WLFramework.Data;
using WLFramework.Data.Linq;
using WLFramework.DataAccess;
using WLFramework.Json;
using WLFramework.Validation;
using WLFramework.Web;

namespace SampleSite.admin.ajax
{
    /// <summary>
    /// deleteOrg 的摘要说明
    /// </summary>
    public class deleteOrg : AjaxHttpHandler
    {

        private class InputData
        {
            [Required]
            public int Id { get; set; }
        }

        public override void OnProcessRequest(HttpContext context)
        {
            InputData input;
            var errors = context.GetModel<InputData>(out input);
            if (errors.Count > 0)
                throw new Exception("输入的数据格式不正确");

            using (PermissionContext db = new PermissionContext())
            {
                db.BeginTransaction();

                delete(db, input.Id);

                db.CommitTransaction();

                context.Response.Write(JSON.Instance.ToJSON(JSONResult.Success));
            }
        }

        public void delete(PermissionContext db, int ID)
        {
            // 删除当前组织架构
            db.sys_Org.Where(k => k.O_ID == ID)
                      .Set(k => k.O_State, 2)
                      .Update();
            var list = db.sys_Positions.Where(k => k.P_Org == ID).ToList();

            // 删除组织下的部门及部门关联信息
            foreach (var item in list)
            {
                db.sys_Positions.Where(k => k.P_ID == item.P_ID)
                                .Set(k => k.P_State, 2)
                                .Update();

                db.sys_UserPosition.Where(k => k.P_ID == item.P_ID)
                                .Set(k => k.P_State, 2)
                                .Update();

                db.sys_PostRoles.Where(k => k.P_ID == item.P_ID)
                                .Set(k => k.R_State, 2)
                                .Update();
            }

            // 递归删除子部门
            var orglist = db.sys_Org.Where(k => k.O_ParentID == ID).ToList();
            foreach (var i in orglist)
            {
                this.delete(db, i.O_ID);
            }
        }
    }
}